package com.vivz.baby.util;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class CommonUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CommonUtil.class);
	
	@SuppressWarnings("unchecked")
	public static final <C extends Collection<E>, E> Collection<C> split(C collection, int offset) {
		
		final Collection<C> collectionOfCollections = new ArrayList<C>();
		
		if (offset > 0) {
			if (CollectionUtils.isNotEmpty(collection)) {
				
				final int size = collection.size();
				LOGGER.debug("Passed collection has a size : [" + size + "]");
				
				C aCollection = (C) new ArrayList<E>();
				int i = 1;
				
				for (E element : collection) {
					aCollection.add(element);
					if (i % offset == 0 || i == size) {
						collectionOfCollections.add(aCollection);
						aCollection = (C) new ArrayList<E>();
					}
					i++;
				}
			} else {
				LOGGER.warn("Empty collection passed.");
			}
		} else {
			LOGGER.warn("Invalid offset[" + offset + "] passed.");
		}
		
		LOGGER.debug("Collection was split into [" + collectionOfCollections.size() + "] collections");
		return collectionOfCollections;
	}
}
